#include <stddef.h>
#include <GL/glew.h>
#include "../Core/Assert.h"
#include "FrameBuffer.h"
#include "RenderTarget.h"
#include "Texture.h"


FrameBuffer::FrameBuffer(const RenderTarget* depthStencil, const Texture* colour0, const Texture* colour1, const Texture* colour2, const Texture* colour3)
{
    glGenFramebuffers(1, &handle);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, handle);
    if (NULL != colour0)
        glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colour0->GetHandle(), 0);
    if (NULL != colour1)
        glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, colour1->GetHandle(), 0);
    if (NULL != colour2)
        glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, colour2->GetHandle(), 0);
    if (NULL != colour3)
        glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, colour3->GetHandle(), 0);
    if (NULL != depthStencil)
        glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencil->GetHandle());
    Assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "GL Error");
}


FrameBuffer::~FrameBuffer()
{
    glDeleteFramebuffers(1, &handle);
}


void BindFrameBuffer(const FrameBuffer* buffer)
{
    if (NULL != buffer)
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer->GetHandle());
    else
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}


void SetFrameBufferMask(bool colour0Enabled, bool colour1Enabled, bool colour2Enabled, bool colour3Enabled)
{
    GLenum attachments[4];
    size_t count = 0;
    if (colour0Enabled)
        attachments[count++] = GL_COLOR_ATTACHMENT0;
    if (colour1Enabled)
        attachments[count++] = GL_COLOR_ATTACHMENT1;
    if (colour2Enabled)
        attachments[count++] = GL_COLOR_ATTACHMENT2;
    if (colour3Enabled)
        attachments[count++] = GL_COLOR_ATTACHMENT3;
    glDrawBuffers(count, attachments);
}
